//https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/
package codeRandomThoughts.Test1047删除字符串中的所有相邻重复项;

import java.util.Arrays;
import java.util.Stack;

public class Solution {
    public String removeDuplicates(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (!stack.isEmpty() && stack.peek() == s.charAt(i)) {
                stack.pop();
                continue;
            }
            stack.push(s.charAt(i));
        }
        StringBuffer stringBuffer = new StringBuffer();
        while (!stack.isEmpty()) {
            stringBuffer.append(stack.pop());
        }
        stringBuffer.reverse();
        return stringBuffer.toString();
    }

    /**
     * 试试双指针
     *
     * @param s
     * @return
     */
    public String removeDuplicates2(String s) {
        char[] chars = s.toCharArray();
        int slow = 0;
        int fast = 1;
        while (fast < s.length()) {
            if (slow < 0 || chars[fast] != chars[slow]) {
                slow++;
                chars[slow] = chars[fast];
            } else {
                slow--;
            }
            fast++;
        }
        return new String(Arrays.copyOfRange(chars,0,slow+1));
    }
}
